package com.econ.powercloud.ems.observer;

import com.econ.powercloud.ems.common.enums.GridRecordStatusEnum;
import com.econ.powercloud.ems.common.interf.ServiceFeedbackDataObserver;
import com.econ.powercloud.ems.common.pojo.EmsMqttReplyVO;
import com.econ.powercloud.ems.dal.entity.EmsGridProcessStep;
import com.econ.powercloud.ems.dal.entity.EmsGridRecordStep;
import com.econ.powercloud.ems.service.biz.EmsGridService;
import com.econ.powercloud.ems.service.dao.EmsGridProcessStepDAO;
import com.econ.powercloud.ems.service.dao.EmsGridRecordStepDAO;
import com.econ.powercloud.ems.util.GridLogUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author : zjf
 * @Description : 服务下发成功与失败处理
 * @Date : 2022/8/12 9:35
 * @Modified by : zjf
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ServiceFeedbackProcessor implements ServiceFeedbackDataObserver {

    private final Integer SUCCESS_CODE = 200;

    private final EmsGridService emsGridService;
    private final EmsGridRecordStepDAO emsGridRecordStepDAO;
    private final EmsGridProcessStepDAO emsGridProcessStepDAO;


    @Override
    public void doInvoke(EmsMqttReplyVO data) {
        EmsGridRecordStep recordStep = emsGridRecordStepDAO.selectByMsgId(data.getMsgId());
        if (null == recordStep) {
            return;
        }
        EmsGridProcessStep processStep = emsGridProcessStepDAO.getById(recordStep.getProcessStepId());
        if (null == recordStep) {
            return;
        }
        log.info("并离网消息消费，接收数据：{}", data);
        //校验当前步骤是否在进行中状态
        if (!recordStep.getStatus().equals(GridRecordStatusEnum.IN_PROGRESS.getCode())) {
            return;
        }
        if (data.getCode().equals(SUCCESS_CODE)) {
            //下发成功
            recordStep.setStatus(GridRecordStatusEnum.SUCCESS.getCode());
        } else {
            //下发失败
            recordStep.setStatus(GridRecordStatusEnum.FAIL.getCode());
        }
        recordStep.setEndTime(new Date());
        recordStep.setLogs(GridLogUtil.getGatewayReplyLog(recordStep.getLogs(),data.getCode().equals(SUCCESS_CODE),processStep.getStepName()));
        emsGridRecordStepDAO.updateById(recordStep);
        //步骤是否执行完成
        emsGridService.checkRecordStepStatus(recordStep);
    }

}
